<!DOCTYPE html>
<html>
<head>
    <meta name="layout" content="main"/>
    <g:set var="entityName" value="${message(code: 'account.label', default: 'account')}"/>
    <title>地图绘制</title>
    <link rel="stylesheet" href="/assets/angular/tree/angular-ui-tree.min.css" />
    <style>
    #wrapper{
        min-height: 0!important;
    }
    /*::-webkit-scrollbar{*/
    /*background: rgb(255,255,255) !important;*/
    /*}*/
    /*::-webkit-scrollbar-button    {*/
    /*background-color:#FF7677;*/
    /*}*/
    body, html{
        width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";
    }
    #content{
        width: 100%;
        top: 50px;
        bottom: 100px;
        position: absolute;
    }
    #allmap{
        width: 100%;
        height:100%;
    }
    #allmap label{max-width:none;}
    #left{
        width: 60%;
        height:100%;
        float: left;
        position: relative;
    }
    #right{
        width: 40%;
        height:100%;
        float: left;
        position: relative;
    }
    .activeAccount{
        background-color: #76D24D;
        color: white;
    }
    .panel-body .select2-choice{
        height: 28px !important;
    }
    .fixed-navbar #wrapper{
        height:100%;
    }
    .citylist_popup_main .city_content_top{
        height: 40px !important;
    }
    .media{
        margin: 0 !important;
    }
    .BMapLabel span{
        position: absolute;
        font-size: 30px;
        left:-13px;
        top:-15px;
    }
    #message{
        margin:0;
        padding:10px 10px;
        text-align: center;
        position: absolute;
        background: #fff;
        overflow-y: scroll;
        height:160px;
        list-style: none;
        display: none;
        opacity: .9;
        border-radius: 4px;
        color: #212121;
        cursor: pointer;
    }
    #message li:hover{
        background: #26b095;
        color:#fff;
        line-height:30px;
    }
    .allCheck{
        background-color: #76D24D;
        border-color: #76D24D;
        color: #fff;
        width: 22px;
        height: 22px;
    }
        .mapcaozuo{
            position: absolute;
            z-index: 10;
            text-size-adjust: none;
            bottom: auto;
            right: 5px;
            top: 5px;
            left: auto;
        }
        .mapcaozuochild{
            height: 47px;
            border-radius: 5px;
            overflow: hidden;
            box-shadow: 1px 1px 3px rgba(0,0,0,0.3);
            float: left;
            background: #f6f6f6;
        }
        .mapManyou{
            border-right: 1px solid #d2d2d2;
            float: left;
            height: 100%;
            width: 64px;
            height: 100%;
            background-image: url("../assets/drow.png");
            background-repeat:no-repeat;
            background-position: center center;
            cursor: pointer;
        }
        .mapDraw{
            border-right: 1px solid #d2d2d2;
            float: left;
            height: 100%;
            width: 64px;
            height: 100%;
            background-image: url("../assets/py.png");
            background-position: center center;
            background-repeat:no-repeat;
            cursor: pointer;
        }
        .mapdel{
            float: left;
            height: 100%;
            width: 64px;
            height: 100%;
            background-image: url("../assets/delMapFeatures.png");
            background-position: center center;
            background-repeat:no-repeat;
            cursor: pointer;
        }
        .mapManyou:hover{
            background-color: #76D24D;
            background-image: url("../assets/drow1.png");
        }
        .mapDraw:hover{
            background-color: #76D24D;
            background-image: url("../assets/py1.png");
        }
        .mapdel:hover{
            background-color: #76D24D;
            background-image: url("../assets/delMapFeatures1.png");
        }
    </style>
</head>
<body class="fixed-navbar fixed-sidebar" >
<div style="width: 100%;height: 100%;overflow: hidden;position: relative;" ng-controller="precinctCtrl">
    <g:include view="map/Mapscript.gsp"/>
    <script type="text/javascript" src="/assets/map/draw/DrawingManager_min.js"></script>
    <link rel="stylesheet" href="/assets/map/draw/DrawingManager_min.css" />
    <!--加载检索信息窗口-->
    <script type="text/javascript" src="/assets/map/draw/SearchInfoWindow_min.js"></script>
    <link rel="stylesheet" href="/assets/map/draw/SearchInfoWindow_min.css" />
    <div class="small-header">
        <div class="hpanel">
            <div class="panel-body">
                <div id="hbreadcrumb" class="pull-right">
                    <ol class="hbreadcrumb breadcrumb">
                        <li>CINDATA PLS</li>
                        <li class="active">
                            <span>地图绘制</span>
                        </li>
                    </ol>
                </div>
                <h2 class="font-light m-b-xs">
                    地图绘制
                </h2>
            </div>
        </div>
    </div>

    <div id="content">
        <div style="width:100%;height:100%;position:relative;">
            <div id="left" >
                <div id="allmap">
                    <div id="doMap" style="display: none;" class="mapcaozuo" style="position: absolute; z-index: 10; text-size-adjust: none; bottom: auto; right: 5px; top: 5px; left: auto;">
                        <div class="mapcaozuochild">
                            <a class="mapManyou" ng-click="drawControl.removeDraw()" title="拖动地图" onfocus="this.blur()"></a>
                            <a class="mapDraw"  ng-click="drawControl.stratDraw('Polygon')" title="画多边形" onfocus="this.blur()"></a>
                            <a class="mapdel"  ng-click="drawControl.clearFeatures()" title="清除所有" onfocus="this.blur()"></a>
                        </div>
                    </div>
                </div>
            </div>
            <div id="right" >
                <div class="hpanel" style="height: 100%;position: relative;">
                    <ul class="nav nav-tabs">
                        <li ng-repeat="pt in precinctTypeArr" ng-class="{'active':isCurPrecinctType(pt)}"><a ng-click="setCurPrecinctType(pt)" ng-cloak>{{pt.name}}</a></li>
                    </ul>
                    <div class="tab-content" style="width:100%;position: absolute;top: 40px;bottom: 0px;">
                        <div ng-repeat="pt in precinctTypeArr" id="{pt.code}" class="tab-pane" ng-class="{'active':isCurPrecinctType(pt)}" style="height: 100%;">
                            <div class="panel-body" style="height: 100%;">
                                <strong>机构树，当前选择机构：{{pt.source.name}}</strong>
                                <div style="position: absolute;top: 35px;left: 20px;right: 20px;bottom: 20px;">
                                    <div style="float: left;width: 50%;height: 100%;overflow-y:auto;">
                                        <div ui-tree data-drag-enabled="false" ng-show="pt.sourceArr.length>0">
                                            <ol ui-tree-nodes ng-model="pt.sourceArr">
                                                <li ng-repeat="node in pt.sourceArr" ui-tree-node  ng-include="'nodes_renderer.html'">
                                                </li>
                                            </ol>
                                        </div>
                                    </div>
                                    <div style="float: left;width: 50%;height: 100%;overflow-y:auto;">
                                        <div ui-tree data-drag-enabled="false" ng-show="pt.customRegionArr.length>0">
                                            <ol ui-tree-nodes ng-model="pt.customRegionArr" >
                                                <li ng-repeat="ocr in pt.customRegionArr" ui-tree-node >
                                                    <div ui-tree-handle class="tree-node tree-node-content" style="border-style: solid;" ng-class="{'activeAccount':isCurCustomRegion(ocr)}" ng-click="setCurCustomRegion(ocr)" >
                                                        {{ocr.name}}
                                                        <a class="pull-right btn btn-xs " ng-click="delete(ocr)"><span style="color: white" class="glyphicon glyphicon-remove"></span></a>
                                                    </div>
                                                </li>
                                            </ol>
                                        </div>
                                    </div>
                                    <div style="clear: both;"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <g:include view="precinct/function.gsp"/>
        </div>

    </div>
</div>
<script type="text/ng-template" id="nodes_renderer.html">
    <div ui-tree-handle class="tree-node tree-node-content" style="border-style: solid;" ng-class="{'activeAccount':isCurSource(node)}" ng-click="setCurSource(node)">
        <a class="btn btn-xs allCheck" ng-if="node.children && node.children.length > 0" data-nodrag="" ng-click="toggle(this)">
            <span class="glyphicon glyphicon-chevron-down" ng-class="{'glyphicon-chevron-right': collapsed,'glyphicon-chevron-down': !collapsed}" style="right: 2.5px; color: #fff;">
            </span>
        </a>
        {{node.name}}
    </div>
    <ol ui-tree-nodes="" ng-model="node.children" ng-class="{hidden: collapsed}" >
        <li ng-repeat="node in node.children" ui-tree-node ng-include="'nodes_renderer.html'">
        </li>
    </ol>
</script>

<script type="text/ng-template" id="precinct_form.html">
    <div class="color-line"></div>
    <div class="modal-header">
        <h4 class="modal-title"><span>添加区域</span><small style="font-size: 14px" class="font-bold"> (注：<span style="color: red">*</span> 为必填)</small></h4>
    </div>
    <div class="form-horizontal" name="myForm">
        <div class="modal-body form-horizontal">
            <div class="form-group">
                <label class="col-md-2 control-label is-required">区域名称</label>
                <div class="col-md-10">
                    <input class="form-control" type="text"  ng-model="data.name"/>
                </div>
            </div>
            <div class="form-group">
                <label class="col-md-2 control-label is-required">所属机构</label>
                <div class="col-md-10">
                    <input class="form-control" type="text"  ng-model="data.sourceName" ng-disabled="true" />
                </div>
            </div>
        </div>
        <div class="modal-footer">
            <button type="button" class="btn btn-default" ng-click="ok()">确定</button>
            <button type="button" class="btn btn-primary" ng-click="cancel()">取消</button>
        </div>
    </div>
</script>

<asset:javascript src="newMap/libs/ol/ol.js" type="text/javascript" />
<g:link href="../../assets/javascripts/newMap/libs/ol/ol.css" rel="stylesheet" type="text/css" />
<asset:javascript src="newMap/libs/ol/xdmap.js" type="text/javascript" />
<g:link href="../../assets/javascripts/newMap/libs/ol/map.css" rel="stylesheet" type="text/css" />
<script>
    %{--点击--}%
    $(".mapManyou").click(function(){
        $(this).css({
            "background-color":"#76D24D",
            "background-image": "url('../assets/drow1.png')"
        })
        $(".mapDraw").css({
            "background-color":"#f6f6f6",
            "background-image": "url('../assets/py.png')"
        })
        $(".mapdel").css({
            "background-color":"#f6f6f6",
            "background-image": "url('../assets/delMapFeatures.png')"
        })
    })
    $(".mapdel").click(function(){
        $(this).css({
            "background-color":"#76D24D",
            "background-image": "url('../assets/delMapFeatures1.png')"
        })
        $(".mapDraw").css({
            "background-color":"#f6f6f6",
            "background-image": "url('../assets/py.png')"
        })
        $(".mapManyou").css({
            "background-color":"#f6f6f6",
            "background-image": "url('../assets/drow.png')"
        })
    })
</script>
<g:javascript>
    window.app.controller("precinctCtrl",function($scope,$timeout,$uibModal){
        $scope.map = null;
        $scope.local = null;
        $scope.overlays = [];
        //绘制控件
        $scope.drawControl = null;
        //地图
        $scope.inputData = {
            currentMap:"AroundAccount",
            keyword: "",
            city:"-1"
        };
        //地图数据
        $scope.cityArr = [];
        $scope.city = null;
        $scope.precinctTypeArr = [
            {
                name: "网点地图" ,
                code: "AroundAccount" ,
                value: "AroundAccount",
                reqUrl: "/precinct/mapAccountData",
                class: 'com.cindata.Account',
                sourceArr: [],
                source: null,
                customRegionArr: []
            },
            {
                name: "开发商楼盘" ,
                code: "Developer" ,
                value: "Developer",
                reqUrl: "/precinct/mapDeveloperData",
                class: 'com.cindata.Developer',
                sourceArr: [],
                source: null,
                customRegionArr: []
            }
        ];
        $scope.precinctType = $scope.precinctTypeArr[0];
        //区块类型数组
        // 初始化地图
        $scope.initMap = function(){
            $scope.initDraw();
            $scope.drawControl.init();
        };
        // //初始化地图图层
        $scope.initOverlay = function(){

        };
        $scope.keySearch = function($event){
            if($event.keyCode === 13){
                $scope.search();
            }
        };
        //切换城市地图事件
        $scope.search = function(){
            //清空搜索
            var zoneNumber = $("#city").val();
            var cityName = $("#city").find("option:selected").text();
            if((!zoneNumber || zoneNumber=="-1") && (!cityName || cityName=="请选择城市")){
                return;
            }
            $scope.drawControl.rqSource = $scope.drawControl.getCityRqSource($("#city").val());
            $scope.drawControl.vector.setSource($scope.drawControl.rqSource);
            $scope.drawControl.switchCity(zoneNumber);
            $scope.drawControl.clearFeatures();
            $scope.searchData();
        };
        //参数改变事件
        $scope.searchData = function() {
            //搜索条件改变事件
            if ($scope.inputData.keyword.trim() == "") {
                return;
            }
            var zoneNumber = $("#city").val();
            var myKeys = $scope.inputData.keyword;
            //$scope.drawControl.fuzzyQuery(zoneNumber, myKeys);
            $scope.drawControl.fuzzyQueryForBank(zoneNumber, myKeys);
        };
        $scope.initDraw = function (){ // 开始绘制
            $scope.drawControl = {
                source: null,
                vector: null,
                rqSource:null,
                draw: null,
                efeature: null,
                init: function () {
                    //阻止双击事件
                    $scope.map.on("dblclick", function (e) {
                        e.preventDefault()
                    }, false);
                    this.source = new ol.source.Vector()
                    this.vector = new ol.layer.Vector({
                        source: this.source
                    });
                    this.rqSource = this.getCityRqSource($("#city").val())
                    this.vector.setSource(this.rqSource);
                    $scope.map.addLayer(this.vector);
                },
                stratDraw: function (type) {
                    if ($scope.precinctType.source == null) {

                        swal('错误', '必须先选择一个所属机构', "error");
                        $scope.drawControl.clearFeatures();
                        return;
                    }
                    this.draw = new ol.interaction.Draw({
                        type: type
                    });
                    this.draw.on('drawend', function (e) {
                        $scope.drawControl.finishDraw(e)
                    }, $scope.map);
                    $scope.map.addInteraction(this.draw);
                    $(".mapDraw").css({
                        "background-color": "#76D24D",
                        "background-image": "url('../assets/py1.png')"
                    })
                    $(".mapManyou").css({
                        "background-color": "#f6f6f6",
                        "background-image": "url('../assets/drow.png')"
                    })
                    $(".mapdel").css({
                        "background-color": "#f6f6f6",
                        "background-image": "url('../assets/delMapFeatures.png')"
                    })
                },
                finishDraw: function (e) {
                    $scope.drawControl.removeDraw();
                    var style = new ol.style.Style({
                        stroke: new ol.style.Stroke({
                            color: 'rgba(250,176,117,1)',
                            width: 2
                        }),
                        fill:new ol.style.Fill({
                            color: 'rgba(255,179,91,0.2)'
                        })
                    });
                    e.feature.setStyle(style);

                    if ($scope.drawControl.rqSource == null) {
                        $scope.drawControl.rqSource = $scope.drawControl.getCityRqSource($("#city").val())
                    }
                    var rqIdList = new Array();
                    var source = $scope.drawControl.rqSource;
                    var polygon = e.feature.getGeometry();
                    var extent = polygon.getExtent();
                    var resultFeatures = source.getFeaturesInExtent(extent);
                    resultFeatures.forEach(function (feature) {
                        var point = feature.getGeometry().getCoordinates();
                        if (polygon.intersectsCoordinate(point)) { // 4.6X版本自带的api
                            rqIdList.push(feature.N.id + "," + feature.N.communityId);
                        }
                    })
                    e.feature.set('idList', rqIdList.join(';'));
                    $scope.drawControl.source.addFeature(e.feature);
                    $scope.drawControl.efeature = e.feature;
                    $scope.afterDraw($scope.drawControl.efeature);

                },
                removeDraw: function () {

                    if (this.draw != null) {
                        $scope.map.removeInteraction(this.draw);
                    }
                },
                addFeature: function (feature) {

                    $scope.drawControl.rqSource.addFeature(feature);

                },
                clearFeatures: function () {
                    this.feature = null;
                    this.source.getFeatures().forEach(function (item) {
                        $scope.drawControl.source.removeFeature(item);
                    })
                },
                switchCity: function (zoneNumber) {
                    var center = null;
                    if (zoneNumber == '330100') {
                        center = ol.proj.transform([120.1551500000, 30.2741500000], 'EPSG:4326', 'EPSG:3857');
                    } else {
                        center = this.getCenter(zoneNumber);
                    }
                    $scope.map.getView().setZoom(10);
                    $scope.map.getView().setCenter(center);
                },
                getCenter: function (id) {
                    var cityId = id.substring(0, 2);
                    var center = null;
                    var url = '../../assets/newMap/data/mapdata/city/' + cityId + '.json';
                    $.ajax({
                        url: url,
                        type: 'GET',
                        async: false,
                        success: function (data) {
                            data.features.forEach(function (item) {
                                if (id == (item.properties.id + '00')) {
                                    center = ol.proj.transform(item.properties.cp, 'EPSG:4326', 'EPSG:3857');
                                    return;
                                }
                            });
                            if (center == null) {
                                center = ol.proj.transform(data.cp, 'EPSG:4326', 'EPSG:3857');
                            }
                        }
                    });
                    return center;
                },
                fuzzyQuery: function (city, name) {
                    //val = '安贞大厦';
                    var filter = ol.format.filter;
                    var request = new ol.format.WFS().writeGetFeature({
                        srsName: 'EPSG:4326',
                        featureNS: 'http://www.xdmap.com',
                        featurePrefix: 'xd',
                        featureTypes: ['POIbeijing_point'],
                        outputFormat: 'application/json',
                        filter: filter.like('NAME', val)
                    });
                    var body = new XMLSerializer().serializeToString(request);
                    fetch('http://10.201.4.84:8088/geoserver/xd/wfs', {
                        method: 'POST',
                        body: body
                    }).then(function (response) {
                        return response.json();
                    }).then(function (json) {
                        var features = new ol.format.GeoJSON().readFeatures(json);
                        features.forEach(function (feature) {
                            var point = ol.proj.transform([parseInt(feature.getProperties().DISPLAY_X), parseInt(feature.getProperties().DISPLAY_Y)], 'EPSG:4326', 'EPSG:3857');
                            var style = new ol.style.Style({
                                stroke: new ol.style.Stroke({
                                    color: 'rgba(250,176,117,1)',
                                    width: 2
                                }),
                                fill:new ol.style.Fill({
                                    color: 'rgba(255,179,91,0.2)'
                                }),
                                text: new ol.style.Text({
                                    font: '14px',
                                    textAlign: 'center',
                                    rotateWithView: true,
                                    text: feature.get('text'),
                                    fill: new ol.style.Fill({
                                        color: 'rgba(255, 255, 255, 1)'
                                    })
                                })
                            });
                            $scope.map.getView().setCenter(point);
                            var cri = new ol.Feature({
                                geometry: new ol.geom.Circle(point, 1000)
                            })
                            cri.setStyle(style)
                            $scope.drawControl.source.addFeature(cri);
                        })
                    });
                },
                fuzzyQueryForBank: function (zoneNumber, name) {
                    function clickMapHref() {
                        $(".mapClick").click(function () {
                            var id = $(this).children('p').attr('id');
                            var x = $(this).children('p').attr('x');
                            var y = $(this).children('p').attr('y');
                            var name = $(this).children('p').attr('name');
                            var center = ol.proj.transform([120.1551500000, 30.2741500000], 'EPSG:4326', 'EPSG:3857');
                            // var center = ol.proj.transform([x,y], 'EPSG:4326', 'EPSG:3857');
                            var result = $scope.findSource(id)
                            if (result) {
                                $scope.map.getView().setCenter(center);
                            }
                        })
                    }

                    $.ajax({
                        url: '/precinct/getAccountInfo',
                        type: 'POST',
                        async: false,
                        data: {
                            name: name,
                            city: zoneNumber
                        },
                        success: function (data) {
                            var content = ""
                            if (data.status == "success") {
                                $("#searchResult").empty();
                                for (var i = 0; i < data.accountList.length; i++) {
                                    content += "<li class='list-group-item media social-profile clearfix p-b-n'>"
                                    content += "<h5 class='pull-left text-center p-n m-n'></h5>"
                                    content +=
                                            "<a class='mapClick'>" +
                                            "名称：" + data.accountList[i].name + "</br>" +
                                            "地址：" + data.accountList[i].address + "</br>" +
                                            "<p style='display:none' x = " + data.accountList[i].x + " y = " + data.accountList[i].y + " name = " + data.accountList[i].name + " id = " + data.accountList[i].id + ">" + "</p>" +
                                            "</a>"
                                    content += "</li>"
                                }
                                $("#searchResult").append(content);
                                clickMapHref()
                            }
                        }
                    })
                },
                getCityRqSource: function (city) {
                    var source = new ol.source.Vector();
                    $.ajax({
                        url: '/precinct/getRqInfoForRegion',
                        async: false,
                        data: {
                            city: city
                        },
                        type: "POST",
                        success: function (data) {
                            //source.set('rqData', data);
                            var features = new Array();
                            data.result.forEach(function (item) {
                                var feature = new ol.Feature({
                                    id: item.id,
                                    communityId: item.community_id,
                                    geometry: new ol.geom.Point([item.x, item.y])
                                })
                                //source.addFeature(feature);
                                feature.setStyle(new ol.style.Style({
                                    zIndex: 99999
                                }))
                                features.push(feature)
                            })
                            source.addFeatures(features)
                        }
                    })
                    $scope.drawControl.rqSource = source;
                    return source;

                }
            }
            var zoneNumber = $("#city").val();
            var center = null;
            if (zoneNumber == '330100') {
                center = ol.proj.transform([120.1551500000, 30.2741500000], 'EPSG:4326', 'EPSG:3857');
            } else {
                center =  $scope.drawControl.getCenter(zoneNumber);
            }
            $scope.map = xdmap.mapInit('allmap',10,center);
        };
        $scope.findSource = function(sourceId) {
            var resultNode = $scope.findSourceFromTree($scope.precinctType.sourceArr, sourceId);
            if (resultNode != null) {
                $scope.setCurSource(resultNode);
                return true;
            } else {
                alert('结果不存在');
                return false;
            }
        };
        $scope.findSourceFromTree = function (sourceArr,id,resultNode) {
            var resultNode = null;
            for (var i = 0; i < sourceArr.length; i++) {
                resultNode = $scope.findSourceFromTreeNode(sourceArr[i], id);
                if(resultNode == null){
                    continue;
                }else{
                    return resultNode;
                }
            }
            return resultNode;
        };
        $scope.findSourceFromTreeNode = function (sourceNode,id) {
            var resultNode = null;
            if (sourceNode.id == id) {
                return sourceNode;
            } else if (sourceNode.children.length > 0) {
                for (var i = 0; i < sourceNode.children.length; i++) {
                    resultNode = $scope.findSourceFromTreeNode(sourceNode.children[i], id);
                    if (resultNode == null) {
                        continue;
                    } else {
                        return resultNode;
                    }
                }
            }
            return resultNode;
        };
        $scope.clearDraw = function(){ // 清除
            $scope.drawControl.removeDraw();
        };
        $scope.initCtrl = function () {
            $("#city").change(function(){
                $scope.inputData.zoneNumber = $(this).val();
                $scope.search();
            });
        };
        $scope.initData = function(){
            $.ajax({
                type: "get",
                url: "/precinct/getInitData",
                data: {},
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        $scope.precinctTypeArr[0].sourceArr = data.accountArr;
                        $scope.precinctTypeArr[1].sourceArr = data.developerArr;
                    },0);

                }
            })
        };
        $scope.toggle = function (scope) {
            scope.toggle();
        };
        $scope.getCustomRegionData = function(params){
            $.ajax({
                type: "get",
                url: "/precinct/getCustomRegionData",
                data: params,
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        $scope.precinctType.customRegionArr = data.customRegionArr;
                    },0);
                    $scope.drawControl.clearFeatures();
                }
            })
        };
        $scope.setCurSource = function(curSource) {
            var level = curSource.level;
            if(level != null) {
                var code = level.code;
                if (code == '4') {
                    $('#doMap').css('display', 'block')
                } else {
                    $('#doMap').css('display', 'none')
                }
            }else {
                $('#doMap').css('display', 'none')
            }
            //父节点定位
            $scope.precinctType.source = curSource;
            $scope.getCustomRegionData({
                sourceId: $scope.precinctType.source.id,
                sourceClass: $scope.precinctType.class
            });
            var cityZoneNumber = curSource.city.zoneNumber;
            var cityName = curSource.city.name
            if (cityZoneNumber) {
                if(cityZoneNumber != $('#city').val()) {
                    $('#city').val(cityZoneNumber);
                    $('#select2-chosen-1').text(cityName);
                    $scope.drawControl.rqSource = $scope.drawControl.getCityRqSource($("#city").val())
                    $scope.drawControl.vector.setSource($scope.drawControl.rqSource);
                }
            }
            var point = [curSource.x, curSource.y];
            var center = ol.proj.transform(point, 'EPSG:4326', 'EPSG:3857');
            if (center) {
                $scope.map.getView().setZoom(16)
                $scope.map.getView().setCenter(center)
                var div = $scope.createDiv(curSource.name)
                var centerOverly = new ol.Overlay({
                    element: div,
                    position: center,
                    offset:[-10,-30],
                    autoPan: true,
                    autoPanAnimation: {
                        duration: 250
                    }
                })
                $scope.map.addOverlay(centerOverly);
            }
        };
        $scope.isCurSource = function(tempSource){
            return ($scope.precinctType.source == tempSource)
        };
        $scope.setCurCustomRegion = function(curCustomRegion){
            $scope.precinctType.customRegion = curCustomRegion;
            $scope.drawControl.clearFeatures();
            $scope.reDrawCustomRegion(curCustomRegion);
        };
        $scope.isCurCustomRegion = function(tempCustomRegion){
            return ($scope.precinctType.customRegion == tempCustomRegion)
        };
        $scope.setCurPrecinctType = function(curPrecinctType){
            $scope.precinctType = curPrecinctType;
        };
        $scope.isCurPrecinctType = function(tempPrecinctType){
            return ($scope.precinctType == tempPrecinctType)
        };
        $scope.afterDraw = function(overlay){
            if($scope.precinctType.source == null){
                swal('错误','必须先选择一个所属机构',"error");
                $scope.drawControl.clearFeatures();
                return false;
            }
            $scope.openForm(overlay);
            return true;
        };
        //重新绘制自定义区域
        $scope.reDrawCustomRegion = function(customRegion) {
            var name = customRegion.name;
            var coordinates = new Array();
            coordinates[0] = new Array();
            var pathStrArr = customRegion.coordinates;
            var arrPath  = pathStrArr.split(';');
            arrPath.forEach(function (points) {
                var point = points.split(',');
                coordinates[0].push(point);
            })
            var feature = new ol.Feature({
                geometry: new ol.geom.Polygon(coordinates),
                text: name,
            })
            var style = new ol.style.Style({
                stroke: new ol.style.Stroke({
                    color: 'rgba(250,176,117,1)',
                    width: 2
                }),
                fill:new ol.style.Fill({
                    color: 'rgba(255,179,91,0.2)'
                }),
                text: new ol.style.Text({
                    font: '14px',
                    textAlign: 'center',
                    rotateWithView: true,
                    text: feature.get('text'),
                    fill: new ol.style.Fill({
                        color: 'rgba(255, 255, 255, 1)'
                    })
                })
            });
            feature.setStyle(style);
            var ext = feature.getGeometry().getExtent();
            var center = ol.extent.getCenter(ext);
            var div =  $scope.createDiv(name)
            var centerOverly = new ol.Overlay({
                element: div,
                position: center,
                offset:[-10,-30],
                autoPan: true,
                autoPanAnimation: {
                    duration: 250
                }
            })
            $scope.map.addOverlay(centerOverly);
            // var radius = 1e6 / Math.pow(2, zoom - 2.3);
            // var label = new ol.Feature({
            //     geometry: new ol.geom.Circle(center, radius),
            //     text: name
            // })
            // label.setStyle(style)
            $scope.drawControl.addFeature(feature);
            //$scope.drawControl.addFeature(label);
            var centerPoint = [customRegion.x, customRegion.y];
            $scope.map.getView().setCenter(centerPoint);
            var zoom  = null;
            zoom = customRegion.zoom;
            if(zoom == null){
                zoom  = 18
            }
            $scope.map.getView().setZoom(zoom);

        };
        $scope.openForm = function(overlay){
            var modalInstance = $uibModal.open({
                animation: true,
                templateUrl: 'precinct_form.html',
                controller: 'precinctFormCtrl',
                size: '',
                resolve: {
                    params: function () {
                       return {
                           source: $scope.precinctType.source,
                           map:$scope.map,
                       };
                    }
                }
            });
            modalInstance.result.then(function (params) {
                var name = params.name;
                var points = overlay.getGeometry().getCoordinates();
                var path = points[0].join(';');
                if(name.length > 40){
                    swal('错误', '名称长度不允许超过20个字', "error");
                    return;
                }
                if(path.length> 1000){
                    swal('错误', '绘制区域过大', "error");
                    return;
                }
                var path = points[0].join(';');
                params.path = path;
                params.type = $scope.precinctType.code;
                params.class = $scope.precinctType.class;
                // var centerPoint = ol.proj.transform(ol.extent.getCenter(overlay.getGeometry().getExtent()),'EPSG:3857', 'EPSG:4326');
                var centerPoint = ol.extent.getCenter(overlay.getGeometry().getExtent());
                params.x = centerPoint[0];
                params.y = centerPoint[1];
                params.zoom =  $scope.map.getView().getZoom();
                params.idList = overlay.get('idList');
                $scope.save(params);
            }, function () {
                $timeout(function(){
                    $scope.drawControl.removeDraw();
                },0);
                console.info('Modal dismissed at: ' + new Date());
            });
        };
        $scope.save = function(params){
            $.ajax({
                type: "post",
                url: "/precinct/saveData",
                data: params,
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        $scope.precinctType.customRegionArr.push(data.customRegion);
                    },0);
                    swal('成功',"增加区域"+data.customRegion.name+"成功",'success');
                }
            });
        };
        $scope.delete = function(customRegion) {
            swalConfirm("确定删除吗？", ("将删除区域" + customRegion.name + "！"), function () {
                $scope.deleteAction(customRegion);
                $scope.drawControl.clearFeatures();
                $scope.map.getOverlays().clear();
            });
        };
        $scope.deleteAction = function(customRegion){
            $.ajax({
                type: "post",
                url: "/precinct/deleteData",
                data: {
                    id: customRegion.id
                },
                success:function (data) {
                    if(!data.success){
                        swal('错误',data.error,'error');
                        return
                    }
                    $timeout(function(){
                        var tempIndex = $scope.precinctType.customRegionArr.indexOf(customRegion);
                        $scope.precinctType.customRegionArr.splice(tempIndex,1);
                    },0);
                }
            });
        };
        $scope.init = function(){
            $scope.initData();
            $scope.initMap();
            $scope.initCtrl();
        };
        $scope.createDiv = function(name) {
            $scope.map.getOverlays().clear();
            var div = this._div = document.createElement("div");
            var img = document.createElement('img');
            img.src = '/assets/accountLogo/zhoubian.png';
            div.style.position = "absolute";
            div.style.cursor = 'pointer';
            div.style.zIndex = '1';
            var message = document.createElement('div');
            message.style.position = 'absolute';
            message.style.border = '1px solid rgb(98, 203, 49)';
            message.style.background = '#fff';
            message.style.borderRadius = '6px';
            message.style.width = '230px';
            message.style.height = '30px';
            message.style.top = '-40px';
            message.style.left = '-98px';
            message.style.textAlign = 'center';
            var header = document.createElement('h5');
            header.innerHTML = name;
            header.style.fontWeight = 'bold';
            header.style.color = '#62cb31';
            message.appendChild(header);
            var sj = this._p = document.createElement("p");
            sj.style.position = "absolute";
            sj.style.width = 0;
            sj.style.height = 0;
            sj.style.borderLeft = "10px solid transparent";
            sj.style.borderRight = "10px solid transparent";
            sj.style.bottom = "-20px";
            sj.style.left = '105px';

            sj.style.borderTop = "10px solid #62cb31";
            message.appendChild(sj);
            div.appendChild(message);
            div.appendChild(img);
            img.onclick = function () {
                $(this).siblings('div').toggle();
            };
            return div;
        }
        $scope.init();
    });
    window.app.controller("precinctFormCtrl",function($scope,$uibModalInstance,params){
        $scope.source = null;
        $scope.map = params.map
        $scope.data = {
            id:"",
            name:"",
            sourceId:"",
            sourceName:""
        };
        $scope.readParams = function(){
            if(params.id){
                $scope.data = params;
            }
            else{
                $scope.source = params.source;
            }
            $scope.data.sourceId = $scope.source.id;
            $scope.data.sourceName = $scope.source.name;
        };
        $scope.ok = function () {
            if($scope.data.name == null || $scope.data.name == ""){
                swal('错误',"区域名称必填",'error');
                return
            }
            $uibModalInstance.close($scope.data);
        };
        $scope.cancel = function () {
            $scope.map.getOverlays().clear();
            $scope.map.getLayers().forEach(function (ly) {
                if(ly.type == 'VECTOR') {
                    var features = ly.getSource().getFeatures();
                    if (features.length > 0) {
                        features.forEach(function (feat) {
                            ly.getSource().removeFeature(feat)
                        })
                    }
                }
            })
            $uibModalInstance.dismiss('cancel');
        };
        $scope.readParams();
    });
</g:javascript>
</body>
</html>
